package org.nfIt.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.nfIt.entity.Article;
import org.nfIt.entity.PageBean;
import org.nfIt.mapper.ArticleMapper;
import org.nfIt.service.ArticleService;
import org.nfIt.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * ClossName:ArticleServiceImpl
 * Pakage:org.nfIt.service.impl
 * Description
 *
 * @Author L
 * @Create 2024/6/5 20:13
 * @Version 2023.1.3
 */
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    /**
     * 添加文章
     * @param article 实体
     * @return
     */
    @Override
    public void add(Article article) {
        //补充属性值
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("id");
        article.setCreateUser(userid);

        articleMapper.add(article);
    }

    /**
     * 动态条件查询sql,使用映射文件完成
     * @param pageNum 总条数
     * @param pageSize 当前页数据集合
     * @param categoryId 创建人id
     * @param state 发布状态
     */
    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {

        //创建pagebean对象，封装数据
        PageBean<Article> pageBean = new PageBean<>();

        //开启分页查询 pagehelper mybatis插件
        PageHelper.startPage(pageNum, pageSize);

        //获取当前登入的id,只可以看到当前用户发表的文章
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userid = (Integer) map.get("id");
        List<Article> list = articleMapper.list(userid,categoryId,state);
        //强转,为什么要强转：因为可以获取PageHelper分页查询后得到的总记录条数和当前页数据
        Page<Article> page = (Page<Article>) list;

        //把数据填充到PageBean对象中
        pageBean.setTotal(page.getTotal());//总条数
        pageBean.setItems(page.getResult());//当前页数据集合
        return pageBean;
    }

    @Override
    public void update(Article article) {
        articleMapper.update(article);
    }

    @Override
    public void delete(Integer id) {
        articleMapper.delete(id);
    }
}
